package site.jlopen.controller.modules;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import site.jlopen.entity.BaseResponse;
import site.jlopen.entity.log.ClientSysLog;

@RestController
@RequestMapping("/log")
public class LogController {

	@Value("${logging.file}")
	private String loggingFile;

	@GetMapping("/list")
	public BaseResponse<List<ClientSysLog>> list(
			@RequestParam(value = "dir", defaultValue = "", required = false) String fileDir) {
		List<ClientSysLog> list = new ArrayList<ClientSysLog>();
		File root = new File(loggingFile + File.separator + fileDir);
		File[] ps = root.listFiles();
		for (File file : ps) {
			long createTime = file.lastModified();
			Date createDate = new Date(createTime);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String createTimeStr = format.format(createDate);
			list.add(new ClientSysLog(file.getName(), file.getAbsolutePath(), file.isDirectory() ? 1 : 0, file.length(),
					createTimeStr));
		}
		return new BaseResponse<List<ClientSysLog>>().success("OK", list);
	}

	/*@GetMapping("/read")
	public ResponseBodyEmitter handle(
			@RequestParam(value = "dir", defaultValue = "", required = false) String fileDir) {
		ResponseBodyEmitter emitter = new ResponseBodyEmitter(-1L);
		CompletableFuture.runAsync(() -> {
			try {
				for (int i = 0; i < 10; i++) {
					System.out.println("bodyEmitter " + i);
					// 发送数据
					emitter.send("bodyEmitter " + i + " @ " + new Date() + "\n");
					Thread.sleep(1000);
				}
				emitter.complete();
			} catch (Exception e) {
				emitter.completeWithError(e);
			}
		});
		return emitter;
	}*/
	
	/*@GetMapping(path = "/read", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
	public SseEmitter handle(
			@RequestParam(value = "dir", defaultValue = "", required = false) String fileDir) {
		SseEmitter emitter = new SseEmitter(-1L);
		CompletableFuture.runAsync(() -> {
			try {
				for (int i = 0; i < 10; i++) {
					System.out.println("bodyEmitter " + i);
					// 发送数据
					SseEmitter.SseEventBuilder event = SseEmitter.event()
							.data("sseEmitter"+i+"@"+LocalTime.now())
							.id(String.valueOf(i))
							.name("sseEmitter");
					emitter.send(event);
					Thread.sleep(1000);
				}
				emitter.complete();
			} catch (Exception e) {
				emitter.completeWithError(e);
			}
		});
		return emitter;
	}*/
	
	/*@GetMapping(path = "/read", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
	public SseEmitter streamFile() {
		SseEmitter emitter = new SseEmitter(-1L);
	    ExecutorService executorService = Executors.newSingleThreadExecutor();
	    executorService.submit(() -> {
	        try {
	            File file = new File("F:\\eclipse2019_workspaces_work4\\secretpad-demo\\logs\\2024-10-18\\info.log");
	            while (true) {
	                BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
	                if (file.exists() ) {
	                    String content = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
	                    emitter.send(SseEmitter.event().data(content));
	                }
	                Thread.sleep(Duration.ofSeconds(10).toMillis()); // 检查文件的间隔时间
	            }
	        } catch (Exception e) {
	            emitter.completeWithError(e);
	        }
	    });
	
	    //emitter.setCompletionTimeout(Duration.ZERO); // 不设置超时
	    return emitter;
	}*/
}
